package org.lds.hotkey.client.autoconfigure.hotkey.report;

import lombok.extern.slf4j.Slf4j;
import org.lds.hotkey.common.model.ReportRuleModel;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;

@Slf4j
public class ReportService {
    private BlockingQueue<ReportRuleModel> queue = new ArrayBlockingQueue<>(10000);

    private AtomicBoolean start = new AtomicBoolean(false);

    public void report(ReportRuleModel reportRuleModel) {
        boolean success = queue.offer(reportRuleModel);
        if (!success) {
            log.info("队列已满,当前key将被丢弃. key={}", reportRuleModel);
        }
    }

    public void start() {
        if (start.get()) return;

        startConsumer();

        start.set(true);
    }

    private void startConsumer() {
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);
        scheduledExecutorService.scheduleAtFixedRate(new ReportTask(queue),0, 500, TimeUnit.MILLISECONDS);
    }
}
